package com.itheima.reggie.common;

import com.itheima.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <b><code>GlobalExceptionHandler</code></b>
 * <p/>
 * 全局异常处理器
 * <p/>
 * <b>Creation Time:</b> 17/06/2024 22:33.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({DuplicateKeyException.class})
    public R<String> duplicateKeyException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        log.error(e.getMessage().substring(e.getMessage().lastIndexOf(":") + 1));
        return R.error(e.getMessage().substring(e.getMessage().lastIndexOf(":") + 1));
    }

    /**
     * 异常处理方法
     * @return 异常信息
     */
    @ExceptionHandler({Exception.class})
    public R<String> excepitonHandler(Exception e, HttpServletRequest request, HttpServletResponse response) {
        return R.error(e.getMessage());
    }

}
